package com.my.financial.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.my.financial.controller.form.LoginForm;
import com.my.financial.controller.form.RegisteForm;
import com.my.financial.domain.FinancialService;
import com.my.financial.domain.User;


@Controller
@SessionAttributes("currUser")
public class UserController {
	@Autowired
	private FinancialService financialService;
	
	@RequestMapping("/check_userName")
	@ResponseBody
	/*==使用@ResponseBody将会跳过视图处理部分，将返回值写入输出流。==*/
	public Boolean check_userName(String userName) {
		return financialService.checkUserName(userName);
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView login2(Model model) {
		return new ModelAndView("login").addObject(new LoginForm());
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(Model model) {
		return new ModelAndView("login").addObject(new LoginForm());
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView doLogin(@Valid LoginForm loginForm,
			BindingResult result, Model model) {
		User user = financialService.login(loginForm);
		if (user == null) {
			result.rejectValue("password","Pattern","* 用户名或密码错误");
		}
		if(result.hasErrors()){
			return new ModelAndView("/login");
		}
		model.addAttribute("currUser", user);
		return new ModelAndView("redirect:/index");
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView register(Model model) {
		return new ModelAndView("register").addObject(new RegisteForm());
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView doRegister(@Valid RegisteForm registeForm,
			BindingResult result,Model model) {
		if(!registeForm.getPassword().equals(registeForm.getRePassword())){
			result.rejectValue("userName","Pattern","* 两次密码输入不一致！");
		}
		if (result.hasErrors()) {
			return new ModelAndView("register").addObject(registeForm);
		}
		financialService.register(registeForm);
		ModelAndView mv = new ModelAndView("redirect:/login");
		return mv;
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public RedirectView logout(SessionStatus sessionStatus) {
		sessionStatus.setComplete();
		return new RedirectView("login");
	}
	
}
